<template>
  <el-dialog
    v-model="state.dialogFormVisible"
    title="上传文件demo"
    custom-class="dialog-min-width"
    width="800px"
    :destroy-on-close="true"
  >
    <el-form ref="formRef" :model="formEdit" :rules="rules" label-width="120px">
      <el-row>
        <el-col :lg="12" :md="24" :sm="24" :xs="24">
          <el-form-item label="单位名称" prop="orgName">
            <el-input v-model="formEdit.orgName" maxlength="64" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="24" :sm="24" :xs="24">
          <el-form-item label="法人代表">
            <el-input
              v-model="formEdit.legalRepresentative"
              maxlength="64"
              clearable
            >
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="24" :sm="24" :xs="24">
          <el-form-item label="机构简介">
            <el-input v-model="formEdit.introduction" maxlength="64" clearable>
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :lg="12" :md="24" :sm="24" :xs="24">
          <el-form-item label="注册金额">
            <el-input-number v-model="formEdit.capital" :min="1" :max="10" />
          </el-form-item>
        </el-col>
        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item label="经营范围">
            <el-input
              v-model="formEdit.businessScope"
              maxlength="64"
              type="textarea"
            >
            </el-input>
          </el-form-item>
        </el-col>

        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item label="单位LOGO">
            <el-upload
              ref="logoFileRef"
              v-model:file-list="logoFileList"
              accept=".jpg,.jpeg,.png,.gif"
              :action="apiUpload.uploadUrl()"
              :headers="headers()"
              :data="{ businessKey: formEdit.id, category: logoFileCategory }"
              :limit="1"
              :before-upload="handleLogoBeforeUpload"
              :on-preview="handleLogoUploadPreview"
              :on-exceed="handleLogoUploadExceed"
              :on-success="handleLogoUploadSuccess"
              list-type="picture-card"
              ><el-icon><Plus /></el-icon
              ><template #tip>
                <div class="el-upload__tip">
                  {{ t("upload.imgTip", { size: 100 }) }}
                </div>
              </template></el-upload
            >
          </el-form-item>
        </el-col>

        <el-col :lg="24" :md="24" :sm="24" :xs="24">
          <el-form-item label="营业执照">
            <el-upload
              ref="licenseFileRef"
              v-model:file-list="licenseFileList"
              accept=".doc,.docx,.ppt,.pptx,.pdf,.zip"
              :action="apiUpload.uploadUrl()"
              :headers="headers()"
              :data="{ businessKey: formEdit.id, category: licenseCategory }"
              :limit="2"
              :before-upload="handleLicenseBeforeUpload"
              :on-preview="handleLicenseUploadPreview"
              :on-exceed="handleLicenseUploadExceed"
              :on-success="handleLicenseUploadSuccess"
              ><el-button type="primary">{{
                t("upload.uploadButton")
              }}</el-button
              ><template #tip>
                <div class="el-upload__tip">
                  doc/ppt/pdf/zip {{ t("upload.fielTipMB", { size: 5 }) }}
                </div>
              </template></el-upload
            >
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="state.dialogFormVisible = false">{{
          t("common.cancelButton")
        }}</el-button>
        <el-button type="primary" @click="handleSubmit">{{
          t("common.submitButton")
        }}</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive } from "vue";
import { Plus } from "@element-plus/icons-vue";
import { headers } from "../../../utils/request";
import apiUpload from "../../admin/api/upload";
import apiUploadDemo from "./upload-demo";
import utils from "../../../utils/utils";
import { useI18n } from "vue-i18n";
const { t } = useI18n({ useScope: "global" });
import { config } from "process";

const formRef = ref();
const formEditOriginal = () => {
  return {
    id: "",
    orgName: "",
    introduction: "",
    businessScope: "",
    capital: 0,
    legalRepresentative: "",
    logoFileId: "",
    fileIds: "",
  };
};
const formEdit = reactive(formEditOriginal());

const logoFileRef = ref();
const logoFileCategory = "demo.logo";
const logoFileList = ref([]);
const licenseFileRef = ref();
const licenseCategory = "demo.license";
const licenseFileList = ref([]);

const state = reactive({
  dialogFormVisible: false,
});

const rules = reactive({
  orgName: [
    {
      required: true,
      message: () => t("common.required"),
      trigger: "blur",
    },
  ],
});

const emit = defineEmits<{
  (event: "on-submit-success", row: any): void;
}>();

const handleLogoBeforeUpload = (file: any) => {
  if (file.type.indexOf("image/") == -1) {
    // console.log("handleLogoBeforeUpload", file, logoFileList.value);
    // utils.infoNotification(t("common.submitSuccess"));
    utils.infoNotification(t("upload.imgType"));
    return false;
  }
  // console.log("file.size", file.size);
  // byte
  if (file.size / 1024 < 100) {
    // 上传图片应小于100K，请重新上传
    utils.infoNotification(t("upload.fileSizeGreater", { size: 100 }));
    return false;
  } else if (file.size / 1024 / 1024 > 5) {
    utils.infoNotification(t("upload.fileSizeLessMB", { size: 5 }));
    return false;
  }
};
const handleLogoUploadPreview = (file: any) => {
  // todo 统一预览页面
  // console.log("handleLogoUploadPreview", file);
  window.open(apiUpload.downloadUrl(file.uid));
};
const handleLogoUploadExceed = (files: any) => {
  // 超过限制数量自动替换旧文件
  // console.log("handleLogoUploadExceed", files);
  logoFileRef.value!.clearFiles();
  const file = files[0] as any;
  logoFileRef.value!.handleStart(file);
  logoFileRef.value!.submit();
};
const handleLogoUploadSuccess = (
  response: any,
  uploadFile: any,
  uploadFiles: any
) => {
  if (response.code == 200) {
    // 更新服务器端主键
    uploadFile.uid = response.data.fileId;
  }
  //uploadFile: {uid:1234, name:"xxx", size:1234, url:"xxx",raw:{}, response:{}}
  // console.log("handleLogoUploadSuccess response", response);
  // console.log("handleLogoUploadSuccess uploadFile", uploadFile);
  // console.log("handleLogoUploadSuccess uploadFiles", uploadFiles);
};

const handleLicenseBeforeUpload = (file: any) => {
  // if (file.type.indexOf("image/") == -1) {
  //   // console.log("handleLogoBeforeUpload", file, logoFileList.value);
  //   // utils.infoNotification(t("common.submitSuccess"));
  //   utils.infoNotification("文件格式错误，请上传图片类型文件");
  //   return false;
  // }
  // console.log("file.size", file.size);
  // byte
  if (file.size / 1024 < 20) {
    utils.infoNotification(t("upload.fileSizeGreater", { size: 20 }));
    return false;
  } else if (file.size / 1024 / 1024 > 5) {
    utils.infoNotification(t("upload.fileSizeLessMB", { size: 5 }));
    return false;
  }
};
const handleLicenseUploadPreview = (file: any) => {
  // todo 统一预览页面
  // console.log("handleLogoUploadPreview", file);
  window.open(apiUpload.downloadUrl(file.uid));
};
const handleLicenseUploadExceed = (files: any) => {
  // 超过限制数量自动替换旧文件
  // console.log("handleLogoUploadExceed", files);
  utils.infoNotification(t("upload.exceeds", { number: 2 }));
};
const handleLicenseUploadSuccess = (
  response: any,
  uploadFile: any,
  uploadFiles: any
) => {
  if (response.code == 200) {
    // 更新服务器端主键
    uploadFile.uid = response.data.fileId;
  }
  //uploadFile: {uid:1234, name:"xxx", size:1234, url:"xxx",raw:{}, response:{}}
  // console.log("handleLogoUploadSuccess response", response);
  // console.log("handleLogoUploadSuccess uploadFile", uploadFile);
  // console.log("handleLogoUploadSuccess uploadFiles", uploadFiles);
};

const handleSubmit = async () => {
  console.log(logoFileList);
  await formRef.value.validate();
  // 统一提交到后台，后台更新文件的状态
  let fileIds = "";
  logoFileList.value.forEach((file) => {
    fileIds += file.uid + ",";
  });
  licenseFileList.value.forEach((file) => {
    fileIds += file.uid + ",";
  });

  formEdit.fileIds = fileIds;
  apiUploadDemo
    .save(formEdit)
    .then((response: any) => {
      if (response.data.code == 200) {
        state.dialogFormVisible = false;
        utils.infoNotification(t("common.submitSuccess"));
        emit("on-submit-success", formEdit);
      }
    })
    .catch((err: any) => {
      utils.errorNotification(t("common.submitException"), err);
    });
};

const show = (id: string) => {
  // console.log(row);
  Object.assign(formEdit, formEditOriginal());

  logoFileList.value = [];
  licenseFileList.value = [];

  if (id != undefined) {
    apiUploadDemo
      .get(id)
      .then((response: any) => {
        if (response.data.code == 200) {
          Object.assign(formEdit, response.data.data);
          if (response.data.files) {
            // 从全部文件列表中按照分类初始化，也可以在后台返回多个分开的结果集
            response.data.files.forEach((file) => {
              if (logoFileCategory == file.category) {
                logoFileList.value.push({
                  uid: file.fileId,
                  name: file.fileName,
                  url: apiUpload.downloadUrl(file.fileId),
                });
              } else if (licenseCategory == file.category) {
                licenseFileList.value.push({
                  uid: file.fileId,
                  name: file.fileName,
                  url: apiUpload.downloadUrl(file.fileId),
                });
              }
            });
          }
        }
      })
      .catch((err: any) => {
        utils.errorNotification(t("common.submitException"), err);
      });
  } else {
    // 前端生成主键
    formEdit.id = utils.getUUID();
  }
  // 触发刷新树
  state.dialogFormVisible = true;
  // 重置表单校验
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

defineExpose({
  show,
});
</script>
